What is the difference between protected, public, package-private, and private in Java?
What is the difference between protected, public, package-private, and private in Java?
19821-Jul-2023
Updated on 22-Jul-2023
Home / DeveloperSection / Forums / What is the difference between protected, public, package-private, and private in Java?
What is the difference between protected, public, package-private, and private in Java?
Aryan Kumar
22-Jul-2023Java has four access modifiers:
The access modifier of a class member (e.g., field, method, or constructor) determines whether the member is accessible to other classes.
Here's a table summarizing the difference between the four access modifiers:
Here are some examples of how to use the different access modifiers:
public
class can be used by any class in any package.protected
class can be used by subclasses of the class in which it is declared, and by classes in the same package.package-private
class can be used by any class in the same package.private
class can only be used by the class in which it is declared.Access modifiers can also be used on class members, such as fields, methods, and constructors. The access modifier of a class member determines whether the member is accessible to other classes.
For example, a
public
field can be accessed by any class, while aprivate
field can only be accessed by the class in which it is declared.Here are some examples of how to use access modifiers on class members:
public
field can be accessed by any class.protected
field can be accessed by subclasses of the class in which it is declared, and by classes in the same package.package-private
field can be accessed by any class in the same package.private
field can only be accessed by the class in which it is declared.Access modifiers are an important part of Java's object-oriented programming model. They allow you to control the visibility of your class members and classes, which can help you to write more secure and maintainable code.